/*
 * @Author: liu.lin liu.lin@hzleaper.com
 * @Date: 2024-03-27 14:28:31
 * @LastEditors: liu.lin liu.lin@hzleaper.com
 * @LastEditTime: 2024-05-31 17:50:40
 * @FilePath: \nest_temp\src\upload\upload.controller.ts
 * @Description:这里主要是写一些有关文件上传或者下载的接口
 */
import {
  Controller,
  Get,
  Post,
  UseInterceptors,
  UploadedFile,
  Res,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { join } from 'path';
import * as fs from 'fs';
import { zip } from 'compressing';
import * as archiver from 'archiver';
// import { GPUDetect } from 'gpu-detect-js';
const si = require('@bigemap/systeminformation');
import type { Response } from 'express';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('ablum')
  @UseInterceptors(FileInterceptor('file'))
  upload(@UploadedFile() file) {
    console.log(`file ${JSON.stringify(file)}`);
    return 'aaaaa';
  }

  @Get('export')
  downLoad(@Res() res: Response) {
    const url = join(
      __dirname,
      '../../imges/1711521765295-2023-02-02_15-44-30-809_NG.JPEG',
    );
    console.log(`url ${url}`);
    console.log(`我在刘林分支改了这里`);

    return res.download(url);
  }

  @Get('stream')
  async down(@Res() res: Response) {
    const url = join(
      __dirname,
      '../../imges/1711521765295-2023-02-02_15-44-30-809_NG.JPEG',
    );
    const tar = new zip.Stream();
    await tar.addEntry(url);
    res.setHeader('Content-Type', 'application/octet-stream');
    tar.pipe(res);
  }

  @Get('export1')
  async downLoads(@Res() res: Response) {
    try {
      const folderPath = join(__dirname, '../../imges/ss');

      // 设置响应头，指定为压缩文件
      res.setHeader('Content-Type', 'application/zip');
      res.setHeader('Content-Disposition', `attachment; filename="files.zip"`);

      // 获取文件夹中的文件列表
      const files = fs.readdirSync(folderPath);
      console.log(`files ${files}`);

      for (const file of files) {
        const filePath = join(folderPath, file);
        const stat = fs.statSync(filePath);

        if (stat.isFile()) {
          const readStream = fs.createReadStream(filePath);
          readStream.pipe(res, { end: false });

          readStream.on('end', () => {
            // 当一个文件传输完成后，继续传输下一个文件
            console.log(`${file} has been sent`);
          });
        }
      }

      // 所有文件发送完成后，结束响应
      res.on('close', () => {
        console.log('Response connection closed');
      });

      res.on('finish', () => {
        console.log('All files have been sent');
      });

      res.on('error', (err) => {
        console.error(`Response error: ${err}`);
      });

      res.on('close', () => {
        console.log('Response connection closed');
      });

      res.end(); // 结束响应
    } catch (error) {
      console.log(`error ${error}`);
    }
  }

  @Get('exportFolder')
  async downLoadFolder(@Res() res: Response) {
    try {
      const folderPath = join(__dirname, '../../imges/ss'); // 要发送的文件夹路径

      // 设置响应头，指定为压缩文件夹
      res.setHeader('Content-Type', 'application/zip');
      res.setHeader('Content-Disposition', `attachment; filename="folder.zip"`);

      const archive = archiver('zip', {
        zlib: { level: 9 }, // 设置压缩级别
      });

      archive.pipe(res);

      // 将文件夹中的内容添加到压缩包中
      archive.directory(folderPath, false);

      // 完成压缩并结束响应
      archive.finalize();
    } catch (error) {
      console.log(`Error: ${error}`);
    }
  }

  @Get('gpu')
  async getGpu() {
    try {
      const gpuData = await si.graphics();
      const hasGPU = gpuData.controllers.length > 0;
      console.log(`gpudata======`, await si.graphics());
      if (hasGPU) {
        console.log(`gpuData`, gpuData);
        const filterGpu = gpuData.controllers.filter((item) => {
          return item.bus !== '';
        });

        console.log('系统存在 GPU。', filterGpu);
        return {
          gpuData: filterGpu,
        };
      } else {
        console.log('系统不存在 GPU。');
      }
    } catch (error) {
      console.error('获取 GPU 信息时出现错误：', error);
    }
  }
  @Get('routepath')
  async getPath() {
    const readDir = fs.readdirSync('C:/Users');
    console.log(readDir);

    const qq = this.getAccessibleDirectories('C:/Users');
    console.log(`qq`, qq);
  }

  getAccessibleDirectories(path) {
    try {
      const items = fs.readdirSync(path);
      console.log(`items`,items);
      
      const accessibleDirectories = [];

      for (const item of items) {
        const itemPath = `${path}/${item}`;
        try {
          fs.accessSync(
            itemPath,
            fs.constants.R_OK |
              fs.constants.W_OK |
              fs.constants.X_OK |
              fs.constants.F_OK,
          ); // 检查读取权限
          if (fs.statSync(itemPath).isDirectory()) {
            accessibleDirectories.push(item);
          }
        } catch (err) {
          // 没有权限访问或不是目录，忽略该项
        }
      }

      return accessibleDirectories;
    } catch (err) {
      console.error('读取文件夹失败:', err);
      return [];
    }
  }
}
